﻿
using System;
using System.Collections;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Xml.Linq;
using System.Text;
using System.Text.RegularExpressions;

namespace Think.Lenovo.Com.AjaxService
{
    /// <summary>
    /// $codebehindclassname$ 的摘要说明
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    public class UploadImages : System.Web.IHttpHandler, System.Web.SessionState.IRequiresSessionState
    {
        public  void ProcessRequest(HttpContext context)
        {
            #region//Step 1. 判断用户是否登录
            
            #endregion

            #region//Step 2.各功能方法的调用
            String doing = context.Request["doing"];
            switch (doing)
            {
                case "1": //上传图片
                    Upload(context);
                    break;
                case "2"://删除图片
                    //do something...
                    DeleteImage(context);
                    break;
                case "3":
                    //do somethign...
                    break;
            }
            #endregion
        }

        /// <summary>
        /// 上传图片
        /// </summary>
        /// <param name="hc"></param>
        private void Upload(HttpContext hc)
        {
            try
            {
                // Get the data
                HttpPostedFile imgFile = hc.Request.Files["Filedata"];

                SaveFile(imgFile.InputStream);
            }
            catch (Exception e)
            {
                // If any kind of error occurs return a 500 Internal Server error
                hc.Response.Write(e.StackTrace);
                hc.Response.StatusCode = 500;
                hc.Response.Write("发生了错误 ^~^ ");
                hc.Response.End();
            }
        }
        /// <summary>
        /// 保存图片，并生成配置文件里指定尺寸大小的缩略图片
        /// </summary>
        /// <param name="fileData"></param>
        private void SaveFile(Stream fileData)
        {
            System.Drawing.Image thumbnail_image = null;
            System.Drawing.Image original_image = null;
            System.Drawing.Bitmap final_image = null;
            System.Drawing.Graphics graphic = null;
            MemoryStream ms = null;
            try
            {
                String imageRoot = ConfigurationManager.AppSettings["CmsImageSiteRoot"].Trim();
                #region//图片文件保存目录
                if (!String.IsNullOrEmpty(imageRoot))
                {
                    while (imageRoot.Length > 1 && (imageRoot[imageRoot.Length - 1] == '\\' || imageRoot[imageRoot.Length - 1] == '/'))
                    {
                        imageRoot = imageRoot.Remove(imageRoot.Length - 1, 1);
                    }
                    imageRoot += @"\";
                }
                #endregion

                #region// Step 1.定义文件的保存目录的子目录以及文件名
                DateTime now = DateTime.Now;

                #region//文件保存的相对路径
                StringBuilder path = new StringBuilder(128);
                path.Append(now.Year)
                        .Append(@"\")
                        .Append(now.Month)
                        .Append(@"\")
                        .Append(now.Day)
                        .Append(@"\")
                        .Append(now.Hour)
                        .Append(@"\")
                        .Append(now.Minute)
                        .Append(@"\");

                #endregion

                #region//文件名
                StringBuilder fileName = new StringBuilder(30);
                fileName.Append(now.Year)
                      .Append(now.Month)
                      .Append(now.Day)
                      .Append(now.Hour)
                      .Append(now.Minute)
                      .Append(now.Second)
                      .Append(now.Millisecond)
                      .Append(".jpg");
                #endregion
                #endregion

                #region// Step 2.读入文件数据
                original_image = System.Drawing.Image.FromStream(fileData);
                #endregion

                #region//Step 3.保存上传上来的原图
                String originImageFolderName = ConfigurationManager.AppSettings["CmsOriginImageFolderName"];
                String originImagePath = imageRoot + originImageFolderName + @"\" + path;

                if (!Directory.Exists(originImagePath))
                {
                    Directory.CreateDirectory(originImagePath);
                }
                original_image.Save(originImagePath + fileName);
                #endregion

                #region//Step 4.生成不同规格的缩略图
                //缩略图
                String imageSize = ConfigurationManager.AppSettings["CmsImageSize"];
                if (!String.IsNullOrEmpty(imageSize))
                {
                    String[] size = imageSize.Split(new char[] { ',', ';' });
                    foreach (String s in size)
                    {
                        if (!String.IsNullOrEmpty(s))
                        {
                            String[] width_height = s.Split(new char[] { 'x', '*' });
                            int width = 0;
                            int height = 0;
                            Int32.TryParse(width_height[0], out width);
                            Int32.TryParse(width_height[1], out height);

                            #region //
                            String thumbnailPath = imageRoot + width + "x" + height + @"\" + path;
                            final_image = new System.Drawing.Bitmap(width, height);
                            graphic = System.Drawing.Graphics.FromImage(final_image);
                            graphic.FillRectangle(new System.Drawing.SolidBrush(System.Drawing.Color.Black), new System.Drawing.Rectangle(0, 0, width, height));

                            graphic.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic; /* new way */
                            //graphic.DrawImage(thumbnail_image, paste_x, paste_y, new_width, new_height);
                            graphic.DrawImage(original_image, 0, 0, width, height);

                            // Store the thumbnail in the session (Note: this is bad, it will take a lot of memory, but this is just a demo)
                            if (!Directory.Exists(thumbnailPath))
                            {
                                Directory.CreateDirectory(thumbnailPath);
                            }
                            final_image.Save(thumbnailPath + fileName, System.Drawing.Imaging.ImageFormat.Jpeg);
                            #endregion

                        }
                    }
                }

                #endregion

                #region//Step 5.输出图片url,以便于前端页面使用图片
                //图片站点域名
                String imgDomainName = ConfigurationManager.AppSettings["CmsImageDomain"];

                //图片站点主目录
                String imgSiteRoot = ConfigurationManager.AppSettings["CmsImageSiteRoot"];

                //前端页面查看的缩略图尺寸
                String viewSize = ConfigurationManager.AppSettings["CmsViewImageSize"];

                String filePath = imageRoot + viewSize + @"/" + path + fileName;

                filePath = filePath.Replace(imgSiteRoot, imgDomainName);

                filePath = filePath.Replace('\\', '/');

                HttpContext.Current.Response.Write(filePath);
                #endregion
            }
            catch (Exception e)
            {
                throw e;
            }
            finally
            {
                // Clean up
                if (final_image != null) final_image.Dispose();
                if (graphic != null) graphic.Dispose();
                if (original_image != null) original_image.Dispose();
                if (thumbnail_image != null) thumbnail_image.Dispose();
                if (ms != null) ms.Close();
            }
        }
        /// <summary>
        /// 删除图片
        /// </summary>
        /// <param name="hc"></param>
        private void DeleteImage(HttpContext hc)
        {
            try
            {
                String imgPath = hc.Request["ImageUrl"];
                if (!String.IsNullOrEmpty(imgPath))
                {
                    //Step 1.得到图片站点域名
                    String imageSiteDomain = ConfigurationManager.AppSettings["CmsImageDomain"].Trim();
                    //Step 2.得到图片站点的主目录
                    String imageSiteRoot = ConfigurationManager.AppSettings["CmsImageSiteRoot"].Trim();
                    //Step 3.得到图片缩略图规格
                    String imageSize = ConfigurationManager.AppSettings["CmsImageSize"].Trim();
                    //Step 4.得到原图存保存目录名
                    String originFolderName = ConfigurationManager.AppSettings["CmsOriginImageFolderName"].Trim();
                    #region//step 5.删除文件
                    List<String> msg = new List<String>();

                    #region//Step 5.1.找到原图文件的路径
                    String pattern = imageSize.Replace(',', '|');
                    Regex reg = new Regex(pattern);
                    imgPath = reg.Replace(imgPath, originFolderName);//原图的url

                    /*
                        将原图的url中的图片站点域名替换成图片站点的主目录路径
                        得到原图片的物理路径
                     */
                    imgPath = imgPath.Replace(imageSiteDomain, imageSiteRoot);
                    #endregion
                    #region//Step 5.2.删除原图文件
                    if (File.Exists(imgPath))
                    {
                        try
                        {
                            File.Delete(imgPath);//删除原图
                            msg.Add("删除原图成功!");
                        }
                        catch
                        {
                            msg.Add("删除原图失败!");
                        }
                    }
                    #endregion
                    #region//Step 5.3.将原图对应的各个缩略图删除
                    if (!String.IsNullOrEmpty(imageSize))
                    {
                        String[] size = imageSize.Split(new char[] { ',' });
                        String thumbnailFolderName = String.Empty;//缩略图目录名
                        foreach (String s in size)
                        {
                            String thumbnailFilePath = String.Empty;//每一个缩略图的路径
                            if (!String.IsNullOrEmpty(s))
                            {
                                String[] width_height = s.Split(new char[] { 'x' });
                                int width = 0;
                                int height = 0;
                                Int32.TryParse(width_height[0], out width);
                                Int32.TryParse(width_height[1], out height);
                                if (width > 0 && height > 0)
                                {
                                    thumbnailFolderName = width + "x" + height;
                                    thumbnailFilePath = imgPath.Replace(originFolderName, thumbnailFolderName);
                                    if (File.Exists(thumbnailFilePath))
                                    {
                                        try
                                        {
                                            File.Delete(thumbnailFilePath);
                                            msg.Add("删除缩略图:" + thumbnailFolderName + " 成功!");
                                        }
                                        catch
                                        {
                                            msg.Add("删除缩略图:" + thumbnailFolderName + " 失败!");
                                        }
                                    }
                                }
                                #region

                                #endregion

                            }
                        }
                    }
                    #endregion
                    #region//Step 5.4. 输出提示消息
                    System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
                    String json = serializer.Serialize(msg);
                    HttpContext.Current.Response.Write(json);
                    #endregion
                    #endregion
                }
            }
            catch (Exception e)
            {
                HttpContext.Current.Response.Write(e.ToString());
            }
        }

        public  bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}
